/*
@Time : 2022/9/14 14:40
@Author : gaozhichang
@File : time_timer_ticker.go
@des: timer,ticker 区别
*/
package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	t1 := time.NewTicker(2 * time.Second)
	t2 := time.NewTimer(2 * time.Second)
	ctx, cancel := context.WithCancel(context.Background())
	tickerRun := func(ctx context.Context) {
		for {
			select {
			case <-t1.C:
				fmt.Println("in ticker period")
			case <-ctx.Done():
				fmt.Println("in ticker period, ctx done")
				return
			}
		}
	}

	timerRun := func(ctx context.Context) {
		for {
			select {
			case <-t2.C:
				fmt.Println("in timer period")
			case <-ctx.Done():
				fmt.Println("in timer period, ctx done")
				return
			}
		}
	}

	//timer只执行一次
	go tickerRun(ctx)
	//ticker 周期性执行
	go timerRun(ctx)

	time.Sleep(10 * time.Second)
	cancel() //退出携程
	time.Sleep(1 * time.Second)
	fmt.Println("main done")
}
